package com.jxd.dianping.common;

import com.jxd.dianping.controller.admin.AdminController;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Aspect
@Configuration
public class ControllerAspect {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    // 环绕式切面 admin包下被打了RequestMapping注解的方法进入切面
    @Around("execution(* com.jxd.dianping.controller.admin.*.*(..)) && @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    // 使用Admin Controller之前的校验
    public Object adminControllerBeforeValidation(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        // 获取方法的签名 然后获取方法
        Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod();
        // 获取方法的AdminPermission注解
        AdminPermission annotation = method.getAnnotation((AdminPermission.class));
        // 没有AdminPermission注解说明是公共方法 直接放行 不需要登录
        if (annotation == null) {
            return proceedingJoinPoint.proceed();
        }
        // 判断管理员是否登录
        String email = (String) request.getSession().getAttribute(AdminController.CURRENT_ADMIN_SESSION);
        // 没有登录
        if (email == null) {
            if (annotation.produceType().equals("text/html")) {
                response.sendRedirect("/admin/admin/loginPage");
                return null;
            } else {
                CommonError commonError = new CommonError(EmBusinessError.ADMIN_SHOULD_LOGIN);
                return CommonRes.create(commonError,"fail");
            }
        } else {
            // 已登录 放行
            return proceedingJoinPoint.proceed();
        }
    }
}
